<template>
  <div class="app-container">

      <el-form class="main-form" v-show="showSearch" ref="queryRef" :model="queryParams" :inline="true" >
          <!-- <el-form-item label="账号ID：" prop="账号ID">
            <el-input v-model="queryParams['账号ID']" placeholder="请输入账号ID" />
          </el-form-item> -->
        <el-form-item v-if="rankFilterConfig.filterList[0] && rankFilterConfig.filterList[0].subCom[0]">
          <el-select class="category-first" v-model="queryParams.category" placeholder="请选择行业类目" style="width: 200px" @change="handleQuery">
            <el-option
              v-for="(option, idx) in rankFilterConfig.filterList[0].subCom[0].list"
              :key="idx"
              :label="option.label"
              :value="option.value + ''"
            />
        </el-select>
        </el-form-item>

         <el-button class="btn-right-top" type="primary" @click="openSyt">生意通后台</el-button>

      </el-form>

      <el-table class="data-list" v-loading="loading" :data="records">
           <el-table-column label="排名" align="center" width="100">
              <template #default="scope">
                <img v-if="scope.row.rankIndex == 1" width="24" height="24" class="rank-icon" src="https://p2-ec.eckwai.com/kos/nlav12333/data-assets/1706532526509.8c0bb2a20a7e0560.png" />
                <img v-else-if="scope.row.rankIndex == 2" width="24" height="24" class="rank-icon" src="https://p2-ec.eckwai.com/kos/nlav12333/data-assets/1706532530961.723cb26adeca9f01.png" />
                <img v-else-if="scope.row.rankIndex == 3" width="24" height="24" class="rank-icon" src="https://p2-ec.eckwai.com/kos/nlav12333/data-assets/1706532536021.0076ad1b7bbc105a.png" />
                <span v-else class="rank-index">{{ scope.row.rankIndex }}</span>
              </template>
            </el-table-column>
            <el-table-column label="商品信息" align="center" width="320">
              <template #default="scope" >
                <div class="product-info">
                  <img :src="scope.row.itemImgUrl" class="product-image" />
                  <div class="info-box">
                    <div class="product-title">{{ scope.row.itemTitle }}</div>
                    <div class="product-price">成交价：￥{{ scope.row.itemPrice }}</div>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="所属店铺	" align="center" width="320">
              <template #default="scope" >
                <div class="user-info">
                  <img :src="scope.row.headUrl" class="user-avatar" />
                  <div class="info-box">
                    <div class="user-name">{{ scope.row.userName }}</div>
                    <div class="user-id"> 快手ID：{{scope.row.userId}}</div>
                  </div>
                </div>
              </template>
            </el-table-column>


            <el-table-column label="成交金额	" align="center">
              <template #default="scope" >
                {{ scope.row.pay_order_amt_a?.value }}
              </template>
            </el-table-column>

            <el-table-column label="点击次数	" align="center">
              <template #default="scope" >
                {{ scope.row.item_click_cnt_a?.value }}
              </template>
            </el-table-column>

            <el-table-column label="成长增速	" align="center">
              <template #default="scope" >
                {{ scope.row.pay_growth_rate?.value }}
              </template>
            </el-table-column>

            <el-table-column label="转化率	" align="center">
              <template #default="scope" >
                {{ scope.row.click_pay_rate?.value }}
              </template>
            </el-table-column>



      </el-table>

      <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="findList"
      />



   </div>
</template>
<script setup lang="ts">
import {reactive, ref, toRefs, onMounted, watch, onUnmounted } from 'vue'
import * as sytService from '@/api/service/SytService'
import { useCookieStore } from '@/stores/cookie'
import pagination from '@/components/pagination/index.vue'
defineOptions({ name: "SytIndex" });

const loading = ref(false)
const showSearch = ref(true)
const cookieStore = useCookieStore()
let loginWindowId: number| null = null;
const webviewId = 'syt'

const rankFilterConfig = ref({
  filterList:[{
    subCom:[{
      list:[{
        key: null,
        label: null,
        value: null
      }]
    }]
  }]
})
const records = ref<any>([])
const total = ref(0);

const data = reactive({
  form: {},
  queryParams: {
    category: '节庆用品/礼品',
    pageNum: 1,
    pageSize: 10,
  }
});

const { queryParams } = toRefs(data)

function openSyt():void{
  globalThis.electronApi.openNewWindow('https://syt.kwaixiaodian.com', {
    width: 1920,
    height: 1080,
    title: '小店生意通'
  });
}

/**
 * 登录
 */
function login(): void {
  globalThis.electronApi.findNewWindow(loginWindowId).then(resp=>{
     if(!resp.success){
      const timeout = 1300;
      loading.value = true;
      setTimeout(()=>{
        loading.value = false
      }, timeout)
      globalThis.electronApi.openNewWindow('https://syt.kwaixiaodian.com', {
        width: 600,
        height: 500,
        minWidth: 600,
        title: '小店生意通',
        resizable: false,
        minimizable: false,
        x: -500,
        timeout: timeout
      },{
        script: `
              document.body.style = 'overflow:hidden';
              window.scrollTo(document.documentElement.scrollWidth - window.innerWidth, 70);

            `
      }).then(resp=>{
        if(resp.success){
          loginWindowId = resp.id;
        }

        console.log(resp)
      })
     }
  })


}

function init(){
  sytService.rankListFilter().then(resp => {
    rankFilterConfig.value = resp;
    findList();
  }).catch(e=>{
    const errMsg = e.error_msg;
    globalThis.error(errMsg||'生意通数据请求失败')
    if(errMsg === '当前登录失效，请重新登录。'){
      login();
    }
  }).finally(()=>{
    loading.value = false;
  })

}

/** 查询列表 */
async function findList() : Promise<any> {

  const conditions:any[] = <any>[];

  if(data.queryParams['账号ID']){
    conditions.push({
      field_name: '账号ID',
      operator: 'is',
      value: [data.queryParams['账号ID']]
    })
  }

  const queryBody = {
    pageSize: data.queryParams.pageSize,
    pageNum: data.queryParams.pageNum,
    categoryLevel1Name:data.queryParams.category,
    itemCategoryByUser:[data.queryParams.category]
  }

  loading.value = true;
  sytService.rankList(queryBody).then(resp => {
    records.value = resp.data;
    total.value = resp.total;
    setTimeout(() => {
      globalThis.electronApi.executeJavaScript(webviewId, `document.querySelector('#quickActive').click();`)
    }, 500);

  }).catch(e=>{
    const errMsg = e.error_msg;
    globalThis.error(errMsg||'生意通数据请求失败')
    if(errMsg === '当前登录失效，请重新登录。'){
      login();
    }
  }).finally(()=>{
    loading.value = false;
  })
}

/** 搜索按钮操作 */
function handleQuery(): void {
  findList()
}


watch(()=>cookieStore.mappings,()=>{
  globalThis.electronApi.closeNewWindow(loginWindowId)
  init();
}, {
  deep: true
})


onMounted(() => {
  init();
  const bounds = { x: 0, y: 0, width: 1, height: 1 };

  globalThis.electronApi.openWebview('https://syt.kwaixiaodian.com/zones/rankingList/slim_product_ranking',{
    id: webviewId,
    bounds: bounds
  },{
    script: `
      /*  setInterval(()=>{
        document.querySelector('#quickActive').click();
      }, 120000); */

    `
  })
})

onUnmounted(() => {
    globalThis.electronApi.closeWebview(webviewId);
})

</script>

<style lang="scss" scoped>
.app-container{
  display: flex;
  flex-direction: column;
}
.app-tables{
  display: flex;
  align-items: center;
  h4{
    font-size: 14px;
    line-height: 14px;
    margin:0;
    padding: 0;
    margin-right: 40px;
    line-height: 36px;
    white-space: nowrap;

  }
  .table-item{
    margin-right: 20px;
    label{
      font-size: 14px;
      margin-right: 10px;
      line-height: 36px;
      font-weight: bold;
    }
  }

}
.main-form{

  position: relative;
  padding-right: 100px;
  .category-second{
    margin-left: 20px;
  }

  .btn-right-top{
    position: absolute;
    right: 20px;
    top: 0px;
  }
}

.data-list{
  flex:1;
}

.product-info{
  width: 300px;
  display: flex;
  .product-image{
    background-blend-mode: #d3d3d305;
    background-color: #d3d3d3;
    background-position: 0, 0;
    background-repeat: no-repeat;
    background-size: 100% 100%;
    border-radius: 6px;
    cursor: pointer;
    height: 64px;
    margin-right: 12px;
    min-width: 64px;
    width: 64px;
  }
  .info-box{
    text-align: left;

    .product-title{
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 2;
      color: #2c2e30;
      color: var(--gray-10, #2c2e30);
      cursor: pointer;
      display: -webkit-box;
      font-size: 14px;
      font-weight: bold;
      line-height: 22px;
      overflow: hidden;
      text-overflow: ellipsis;
      word-break: break-all;
    }

    .product-price{
      margin-top: 4px;
      color: #90949e;
      font-size: 12px;
      line-height: 20px;
    }
  }
}

.user-info{
  width: 300px;
  display: flex;
  .user-avatar{
    background-blend-mode: #d3d3d305;
    background-color: #d3d3d3;
    background-position: 0, 0;
    background-repeat: no-repeat;
    background-size: 100% 100%;
    border-radius: 6px;
    cursor: pointer;
    height: 64px;
    margin-right: 12px;
    min-width: 64px;
    width: 64px;
  }
  .info-box{
    text-align: left;

    .user-name{
      color: #2c2e30;
      flex: 1 1;
      font-size: 14px;
      font-weight: 700;
      line-height: 22px;
      max-width: -webkit-fit-content;
      max-width: -moz-fit-content;
      max-width: fit-content;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .user-id{
      margin-top: 4px;
      color: #90949e;
      font-size: 12px;
      line-height: 20px;
    }
  }
}

</style>
